package com.woniuxy.config;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@ServerEndpoint("/WebSocketHandler/{userName}")		//表示接受的是STOMP协议提交的数据
public class WebSocketHandler {

    //建立连接
    @OnOpen
    public void openSession(@PathParam("userName")String userName, Session session) {
        //消息
        System.out.println("测试"+  "欢迎:"+userName+"加入群聊");
        String message = "欢迎:"+userName+"加入群聊";
        //加入聊天室
        WebSocketUtil.MESSAGEMAP.put(userName, session);

        //发送消息
        WebSocketUtil.sendMessageToAll(message);
    }

    @OnMessage
    public void onMessage(@PathParam("userName")String userName,String message) {
        System.out.println("测试"+  "OnMessage:"+userName+"加入群聊");
        message = userName+":"+message;
        WebSocketUtil.sendMessageToAll(message);
    }

    //离开聊天室
    @OnClose
    public void onClose(@PathParam("userName")String userName,Session session) {
        //将当前用户从map中移除 注销
        WebSocketUtil.MESSAGEMAP.remove(userName);
        //群发消息
        WebSocketUtil.sendMessageToAll("用户:"+userName+"离开聊天室");
        //关闭session
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //连接异常
    @OnError
    public void onError(Session session,Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}